// JSON-RPC 2.0控制器
const config = require('../config');

class JsonRpcController {
  constructor() {
    // 保存已连接的客户端信息
    this.connectedClients = new Map();
    this.serverStartTime = new Date();
    
    // 注册可用的方法
    this.methods = {
      // 基础连接服务
      'connect': this.connect.bind(this),
      'disconnect': this.disconnect.bind(this),
      'heartbeat': this.heartbeat.bind(this),
      'getStatus': this.getStatus.bind(this),
      
      // 扩展服务
      'processData': this.processData.bind(this),
      'logMessage': this.logMessage.bind(this),
      'sendMetrics': this.sendMetrics.bind(this),
      'sendNotification': this.sendNotification.bind(this)
    };
  }
  
  // 处理JSON-RPC请求
  async handleRequest(req, res) {
    const body = req.body;
    
    // 验证是否为有效的JSON-RPC 2.0请求
    if (!body || body.jsonrpc !== '2.0' || !body.method) {
      return res.json({
        jsonrpc: '2.0',
        error: {
          code: -32600,
          message: 'Invalid Request'
        },
        id: body?.id || null
      });
    }
    
    const { method, params, id } = body;
    
    // 检查方法是否存在
    if (!this.methods[method]) {
      return res.json({
        jsonrpc: '2.0',
        error: {
          code: -32601,
          message: 'Method not found'
        },
        id: id || null
      });
    }
    
    try {
      // 调用对应的方法
      const result = await this.methods[method](params);
      
      // 如果是通知（id为null），则不需要返回结果
      if (id === null) {
        return res.status(204).end();
      }
      
      // 返回成功结果
      return res.json({
        jsonrpc: '2.0',
        result,
        id
      });
    } catch (error) {
      // 返回错误结果
      return res.json({
        jsonrpc: '2.0',
        error: {
          code: error.code || -32000,
          message: error.message || 'Server error',
          data: error.data
        },
        id: id || null
      });
    }
  }
  
  // 客户端连接
  connect(params) {
    const { clientId, clientVersion } = params || {};
    
    if (!clientId) {
      throw { code: -32602, message: '缺少客户端ID', data: { field: 'clientId' } };
    }
    
    // 记录连接信息
    console.log(`客户端 ${clientId} (版本: ${clientVersion || 'unknown'}) 已连接 (JSON-RPC)`);
    
    // 存储客户端信息
    this.connectedClients.set(clientId, {
      clientId,
      clientVersion,
      connectedAt: new Date(),
      lastHeartbeat: new Date()
    });
    
    // 返回连接成功响应
    return {
      status: 'connected',
      message: 'MCP连接已建立',
      serverId: config.server.serverId || 'MCP-Server-1.0',
      timestamp: new Date().toISOString()
    };
  }
  
  // 客户端断开连接
  disconnect(params) {
    const { clientId } = params || {};
    
    if (!clientId) {
      throw { code: -32602, message: '缺少客户端ID', data: { field: 'clientId' } };
    }
    
    // 从已连接客户端中移除
    this.connectedClients.delete(clientId);
    
    console.log(`客户端 ${clientId} 已断开连接 (JSON-RPC)`);
    
    return {
      status: 'disconnected',
      message: 'MCP连接已关闭',
      timestamp: new Date().toISOString()
    };
  }
  
  // 心跳检测
  heartbeat(params) {
    const { clientId } = params || {};
    
    if (!clientId) {
      throw { code: -32602, message: '缺少客户端ID', data: { field: 'clientId' } };
    }
    
    // 更新客户端心跳时间
    const client = this.connectedClients.get(clientId);
    if (client) {
      client.lastHeartbeat = new Date();
    } else {
      // 如果客户端不存在，自动连接
      this.connectedClients.set(clientId, {
        clientId,
        connectedAt: new Date(),
        lastHeartbeat: new Date()
      });
    }
    
    return {
      status: 'alive',
      timestamp: new Date().toISOString(),
      message: '心跳检测成功'
    };
  }
  
  // 获取服务器状态
  getStatus() {
    // 计算服务器运行时间
    const uptime = (new Date() - this.serverStartTime) / 1000; // 秒
    
    return {
      status: 'running',
      serverId: config.server.serverId || 'MCP-Server-1.0',
      version: config.server.version || '1.0.0',
      uptime: Math.floor(uptime),
      connectedClients: this.connectedClients.size,
      memory: process.memoryUsage(),
      timestamp: new Date().toISOString()
    };
  }
  
  // 数据处理服务
  processData(params) {
    const { clientId, data } = params || {};
    
    if (!clientId) {
      throw { code: -32602, message: '缺少客户端ID', data: { field: 'clientId' } };
    }
    
    if (!data) {
      throw { code: -32602, message: '缺少数据', data: { field: 'data' } };
    }
    
    console.log(`客户端 ${clientId} 请求数据处理服务 (JSON-RPC)`);
    
    // 模拟数据处理
    const result = {
      processedData: `处理后的数据: ${data}`,
      processingTime: Math.random() * 100, // 模拟处理时间
      status: 'completed'
    };
    
    return {
      status: 'success',
      result,
      timestamp: new Date().toISOString(),
      message: '数据处理服务完成'
    };
  }
  
  // 日志服务
  logMessage(params) {
    const { clientId, logType, logMessage } = params || {};
    
    if (!clientId) {
      throw { code: -32602, message: '缺少客户端ID', data: { field: 'clientId' } };
    }
    
    if (!logMessage) {
      throw { code: -32602, message: '缺少日志内容', data: { field: 'logMessage' } };
    }
    
    console.log(`客户端 ${clientId} 发送日志: [${logType || 'INFO'}] ${logMessage} (JSON-RPC)`);
    
    return {
      status: 'success',
      logId: `log-${Date.now()}`,
      timestamp: new Date().toISOString(),
      message: '日志已记录'
    };
  }
  
  // 监控服务
  sendMetrics(params) {
    const { clientId, metrics } = params || {};
    
    if (!clientId) {
      throw { code: -32602, message: '缺少客户端ID', data: { field: 'clientId' } };
    }
    
    console.log(`客户端 ${clientId} 发送监控数据 (JSON-RPC)`);
    
    // 模拟系统监控数据
    const systemMetrics = {
      cpu: Math.random() * 100,
      memory: Math.random() * 100,
      disk: Math.random() * 100,
      network: Math.random() * 100
    };
    
    return {
      status: 'success',
      clientMetrics: metrics || {},
      systemMetrics,
      timestamp: new Date().toISOString(),
      message: '监控数据已接收并处理'
    };
  }
  
  // 通知服务
  sendNotification(params) {
    const { clientId, target, message } = params || {};
    
    if (!clientId) {
      throw { code: -32602, message: '缺少客户端ID', data: { field: 'clientId' } };
    }
    
    if (!message) {
      throw { code: -32602, message: '缺少通知内容', data: { field: 'message' } };
    }
    
    console.log(`客户端 ${clientId} 发送通知: "${message}" 到 ${target || '所有客户端'} (JSON-RPC)`);
    
    return {
      status: 'success',
      notificationId: `notify-${Date.now()}`,
      deliveryStatus: 'sent',
      timestamp: new Date().toISOString(),
      message: '通知已发送'
    };
  }
}

// 创建单例实例
const jsonRpcController = new JsonRpcController();

module.exports = jsonRpcController; 